/**
*
* Licensed Property to CMB Co., Ltd.
* 
* (C) Copyright of CMB Co., Ltd. 2010
*     All Rights Reserved.
*
* 
* Modification History:
* =============================================================================
*   Author         Date          Description
*   ------------ ---------- ---------------------------------------------------
*   wshe       2019-03-20      MPI工具类
* =============================================================================
*/
package com.fingard.dsp.bank.directbank.cmb04.util;

import java.io.UnsupportedEncodingException;
import java.security.PublicKey;
import java.util.Map;
/**
* 
* @ClassName SDKUtil
* @Description acpsdk工具类
* 声明：以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己需要，按照技术文档编写。该代码仅供参考，不提供编码，性能，规范性等方面的保障<br>
*/
public class SDKUtil {

	
	/**
	 * 判断字符串是否为NULL或空
	 * 
	 * @param s
	 *            待判断的字符串数据
	 * @return 判断结果 true-是 false-否
	 */
	public static boolean isEmpty(String s) {
		return null == s || "".equals(s.trim());
	}
	
	
	/**
	 * 根据signMethod的值，提供三种计算签名的方法
	 * 
	 * @param data_map
	 *            待签名字符串和签名结果map
	 * @return 签名是否成功
	 */
	public static boolean sign(Map<String,String> data_map ) {
		String encoding="gbk";
		String data_str=data_map.get(SDKUtil.param_data);
		//System.out.println("待签名请求报文串:[" + data_str + "]");
		byte[] byteSign = null;
		String stringSign = null;
		try {
			// 通过SHA256进行摘要并转16进制
			byte[] signDigest = SecureUtil
					.sha256X16(data_str, encoding);
			byteSign = SecureUtil.base64Encode(SecureUtil.signBySoft256(
					CertUtil.getSignCertPrivateKey(), signDigest));
			stringSign = new String(byteSign);
			//System.out.println("签名："+ stringSign);
			// 设置签名域值
			data_map.put(SDKUtil.param_signature, stringSign);
			return true;
		} catch (Exception e) {
			System.out.println("Sign Error" + e);
			return false;
		}
	}

	

	
	/**
	 * 验证签名
	 * 
	 * @param resData
	 *            返回报文数据
	 * @param encoding
	 *            编码格式
	 * @return
	 */
	public static boolean validate(Map<String, String> resData) {

		String encoding = "UTF-8";
		String data_str = resData.get(SDKUtil.param_data);
		String sign_str = resData.get(SDKUtil.param_signature);
		
		// 验签
		//System.out.println("签名原文：["+sign_str+"]");


		try {
			PublicKey pubKey=CertUtil.getValidateCertPublicKey();
			// 验证签名需要用银行发给商户的公钥证书.
			boolean result = SecureUtil.validateSignBySoft256(pubKey, 
					SecureUtil.base64Decode(sign_str
					.getBytes(encoding)), SecureUtil.sha256X16(
							data_str, encoding));
			//System.out.println("验证签名" + (result? "成功":"失败"));
			return result;
		} catch (UnsupportedEncodingException e) {
			System.out.println(e.getMessage()+ e);
		} catch (Exception e) {
			System.out.println(e.getMessage()+ e);
		}
		
		
		return false;
	}
	
	
	/** 签名公钥证书 */
	public static final String param_signature = "signature";
	
	/** 签名公钥证书 */
	public static final String param_data = "message";
}
